//
//  NetWorkManager.swift
//  ShoppingMall
//
//  Created by 余潇逸 on 2017/12/6.
//  Copyright © 2017年 小鱼儿. All rights reserved.
//

import UIKit
import Alamofire
import AlamofireObjectMapper
import ObjectMapper

import Moya
import RxSwift

enum BaiduApiMethod: String {
    case post = "post"
    case get = "get"
}

public struct NetWorkManager {
    
    private var httpHeader: [String: String] = {
        var dic = [String: String]()
//        dic["token"] = UserInfo.share().token
        return dic
    }()
    
    private let failureResultDic: [String : Any] = ["result": -1,
                                                    "message": "网络暂时不通畅，请稍后再试"]
    private let disposeBag = DisposeBag()
    
    var parameters: [String: Any] = {
        var dic = [String: Any]()
        if let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String {
            dic["version"] = version
        }
        dic["platform"] = "ios"
//        dic["token"] = UserInfo.share().token
        return dic
    }()
    
    mutating func addParameter(_ key: String, value: Any?) {
        parameters[key] = value
    }
    
    func request<T: Mappable>(api: Api,
                              apiIsFull: Bool = false,
                              method: HTTPMethod = .post,
                              complectionHandler: @escaping (T) -> Void) {
        printLog(api.url + NetWorkManager.parsingParams(param: self.parameters))
        
        
        
        Alamofire.request(!apiIsFull ? api.url: api.fullUrl, method: method, parameters: parameters, encoding: URLEncoding.default, headers: httpHeader).responseObject { (resp: DataResponse<T>) in
            if let resultData = resp.data {
                let string = String(data: resultData, encoding: String.Encoding.utf8) ?? ""
                printLog(string)
                if let result = Mapper<BaseData>().map(JSONString: string) {
                    if result.code == 400 {
//                        k_win.showHUD(result.message)
//                        k_win.rootViewController?.present(NaviVC(rootViewController:LoginVC()), animated: true, completion: nil)
                    }
                }
            }
            
            guard let resultValue = resp.result.value else {
                if let failureValue = Mapper<T>().map(JSON: self.failureResultDic) {
                    complectionHandler(failureValue)
                }
                return
            }
            
            complectionHandler(resultValue)
        }
    }
    
    func upload<T: Mappable>(image: UIImage,
                             api: Api,
                             method: HTTPMethod = .post,
                             complectionHandler: @escaping (T) -> Void) {
        if let imageData = UIImagePNGRepresentation(image) {
            Alamofire.upload(multipartFormData: { (data) in
                data.append(imageData, withName: "", mimeType: "img")
            }, usingThreshold: 0, to: api as! URLConvertible, method: method, headers: httpHeader, encodingCompletion: { (result) in
                
            })
        }
    }
    
    static func parsingParams(param: [String: Any]) -> String {
        var paramString = "?"
        var index = 0
        param.forEach { (key, value) in
            index += 1
            paramString.append("\(key)=\(value)")
            if index < param.count {
                paramString.append("&")
            }
        }
        return paramString
    }
}
